package com.beesphere.products.throttling.processor.async;

import java.util.concurrent.CountDownLatch;

import com.beesphere.products.throttling.AsyncCallback;
import com.beesphere.products.throttling.UnitOfWork;

/**
 * Helper methods for AsyncProcessor objects.
 */
public final class AsyncProcessorHelper {
    
    private AsyncProcessorHelper() {
        // utility class
    }

    /**
     * Calls the async version of the processor's process method and waits
     * for it to complete before returning. This can be used by AsyncProcessor
     * objects to implement their sync version of the process method.
     */
    public static boolean process (AsyncProcessor processor, UnitOfWork unitOfWork) throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);
        boolean sync = processor.process (unitOfWork, 0L, new AsyncCallback () {
            private static final long serialVersionUID = -4811197707747289287L;
			public void done (Object unitOfWorkResult, boolean sync) {
                if (!sync) {
                    latch.countDown();
                }
            }
        });
        if (!sync) {
            latch.await();
        }
        return sync;
    }
}
